#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main() {
  Mat src = imread("../images/2.jpg");
  if (src.empty()) {
    cout << "could not load image.." << endl;
    return -1;
  }
  namedWindow("opencv setup demo", CV_WINDOW_AUTOSIZE);
  imshow("opencv setup demo", src);

  Mat gray_src;
  cvtColor(src, gray_src, CV_BGR2GRAY);
  namedWindow("output", CV_WINDOW_AUTOSIZE);
  imshow("output", gray_src);

  // 单通道
  /*
  int height = gray_src.rows;
  int width = gray_src.cols;
    for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
      int gray = gray_src.at<uchar>(row, col);
      gray_src.at<uchar>(row, col) = 255 - gray;
    }
  }
  imshow("gray", gray_src);
  */
  // 三通道
  Mat dst;
  dst.create(src.size(), src.type());
  int height = src.rows;
  int width = src.cols;
  int nc = src.channels();

  for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
      if (nc == 1) {
        int gray = gray_src.at<uchar>(row, col);
        src.at<uchar>(row, col) = 255 - gray;
      } else {
        int b = src.at<Vec3b>(col, row)[0];
        int g = src.at<Vec3b>(col, row)[1];
        int r = src.at<Vec3b>(col, row)[2];
        dst.at<Vec3b>(col, row)[0] = 255 - b;
        dst.at<Vec3b>(col, row)[1] = 255 - g;
        dst.at<Vec3b>(col, row)[2] = r;

        // 值最大变灰
        gray_src.at<uchar>(row, col) = max(r, max(b, g));
      }
    }
  }
  imshow("output", dst);
  imshow("output2", gray_src);
  // api
  Mat dst1;
  bitwise_not(src, dst1);
  imshow("output1", dst1);

  waitKey(0);
  return 0;
}